package com.android.xcalendar;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.android.xcalendar.R;
import com.android.xcalendar.activity.MonthViewActivity;
import com.android.xcalendar.util.XCalendarContentManager;

public class C2DMReceiver extends BroadcastReceiver{
	//
	private static final String TAG="C2DMReceiver";
	//
	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		if(intent.getAction().equals("com.google.android.c2dm.intent.REGISTRATION")){
			handleRegistration(context, intent);
		}else if(intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")){
			
			handleMessage(context, intent);
		}
	}
	
	private void handleRegistration(final Context context, Intent intent){
		final String registrationId = intent.getStringExtra("registration_id");
        String error = intent.getStringExtra("error");
        String removed = intent.getStringExtra("unregistered");
        Log.v(TAG, "handleRegistration");
        Log.v(TAG, "dmControl: registrationId = " + registrationId +
                ", error = " + error + ", removed = " + removed);
        //
        if(removed != null){
        	onUnregistrated(context);
        	return;
        }else if(error != null){
        	onError(context, error);
        	return;
        }else{
        	onRegistrated(context, registrationId);
        }
        
	}
	private void handleMessage(Context context, Intent intent){
		onMessage(context, intent);
	}
	private void onRegistrated(Context context, String registrationId){
		Log.v(TAG, "C2DMReceiver Register with the registrationId = " + registrationId);
		C2DMRegistration.setRegistraionID(context, registrationId);
		XCalendarContentManager.getInstance().registerC2DMId(registrationId);
	}
	private void onUnregistrated(Context context){
		Log.v(TAG, "C2DMReceiver Unregister");
    	C2DMRegistration.clearRegistrationId(context);
	}
	private void onError(Context context, String errorId){
		Log.v(TAG, "C2DMReceiver Error with the reason: " + errorId);
		C2DMRegistration.clearRegistrationId(context);
		if("SERVICE_NOT_AVAILABLE".equals(errorId)){
			long backoffTimeMs = C2DMRegistration.getBackoff(context);
			Intent retryIntent = new Intent("com.google.android.c2dm.intent.RETRY");
			PendingIntent retryPIntent = PendingIntent.getBroadcast(context, 
                    0 /*requestCode*/, retryIntent, 0 /*flags*/);
            AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            am.set(AlarmManager.ELAPSED_REALTIME,
                    backoffTimeMs, retryPIntent);
            backoffTimeMs *= 2;
            C2DMRegistration.setBackoff(context, backoffTimeMs);
		}
		
		
	}
	private void onMessage(Context context, Intent intent){
		Log.v(TAG, "C2DMReceiver Message");
		Bundle extras = intent.getExtras();
		if(extras!=null){
			String msg = (String)extras.get(MonthViewActivity.MESSAGE_KEY_ONE);
			Log.v(TAG, "The received msg = "+msg);
			NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
			Notification notification = new Notification(R.drawable.icon, "New Event comes...", System.currentTimeMillis());
			PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, MonthViewActivity.class), 0);
			notification.setLatestEventInfo(context, context.getString(R.string.app_name), msg, contentIntent);
			notificationManager.notify(0, notification);
			Intent intentA = new Intent();
			intentA.putExtra("message", msg);
			intentA.setAction("android.intent.action.test");
			context.sendBroadcast(intentA);
		}
	}
}
